// SPDX-License-Identifier: GPL-2.0+

#include <asm/io.h>
#include <common.h>
#include <i2c.h>

#include "sii9022a.h"

#define PIXEL_CLK_LSB_REG		0x00
#define PIXEL_CLK_MSB_REG		0x01
#define VERT_FREQ_LSB_REG		0x02
#define VERT_FREQ_MSB_REG		0x03
#define TOTAL_PIXELS_LSB_REG		0x04
#define TOTAL_PIXELS_MSB_REG		0x05
#define TOTAL_LINES_LSB_REG		0x06
#define TOTAL_LINES_MSB_REG		0x07
#define TPI_INBUS_FMT_REG		0x08
#define TPI_INPUT_FMT_REG		0x09
#define TPI_OUTPUT_FMT_REG		0x0A
#define TPI_SYS_CTRL_REG		0x1A
#define TPI_PWR_STAT_REG		0x1E
#define TPI_AUDIO_HANDING_REG		0x25
#define TPI_AUDIO_INTF_REG		0x26
#define TPI_AUDIO_FREQ_REG		0x27
#define TPI_SET_PAGE_REG		0xBC
#define TPI_SET_OFFSET_REG		0xBD
#define TPI_RW_ACCESS_REG		0xBE
#define TPI_TRANS_MODE_REG		0xC7

/* Programming of Silicon SIi9022a HDMI Transmitter */
int sii9022a_set_dvi_encoder(void)
{
	unsigned char id0;
	unsigned char id1;
	unsigned char id2;
	unsigned char data = 0;
	int i;

	i2c_set_bus_num(1);

	i2c_write(CONFIG_SYS_I2C_SII9022A_ADDR, TPI_TRANS_MODE_REG, 1, &data, 1);
/*
	i2c_read(CONFIG_SYS_I2C_SII9022A_ADDR, 0x1b, 1, &id0, 1);
	i2c_read(CONFIG_SYS_I2C_SII9022A_ADDR, 0x1c, 1, &id1, 1);
	i2c_read(CONFIG_SYS_I2C_SII9022A_ADDR, 0x1d, 1, &id2, 1);

	printf("Sii9022a: ID 0x%02x 0x%02x 0x%02x\n", id0, id1,id2);

	if (id0 != 0xb0 || id1 != 0x2 || id2 != 0x3) {
		printf("ID Err\n");
		return -1;
	}
*/
	i2c_read(CONFIG_SYS_I2C_SII9022A_ADDR, TPI_PWR_STAT_REG, 1, &data, 1);
	data &= ~(0x3);
	i2c_write(CONFIG_SYS_I2C_SII9022A_ADDR, TPI_PWR_STAT_REG, 1, &data, 1);

	/* Active TMDS Output */
	i2c_read(CONFIG_SYS_I2C_SII9022A_ADDR, TPI_SYS_CTRL_REG, 1, &data, 1);
	data &= ~(1 << 4);
	i2c_write(CONFIG_SYS_I2C_SII9022A_ADDR, TPI_SYS_CTRL_REG, 1, &data, 1);

	/* Force switch Bus to DDC in order to enable EDID reading */
	i2c_read(CONFIG_SYS_I2C_SII9022A_ADDR, TPI_SYS_CTRL_REG, 1, &data, 1);
	data |= (1 << 2);	//Bus requst
	i2c_write(CONFIG_SYS_I2C_SII9022A_ADDR, TPI_SYS_CTRL_REG, 1, &data, 1);

	for (i = 0; i < 30; i++) {
		i2c_read(CONFIG_SYS_I2C_SII9022A_ADDR, TPI_SYS_CTRL_REG, 1, &data, 1);
		if (data & (1 << 1)) {
//			printf("Sii9022a: Managed get DDC Bus\n");
			/* Ack bus switching */
			data = 0x06;
			i2c_write(CONFIG_SYS_I2C_SII9022A_ADDR, TPI_SYS_CTRL_REG, 1, &data, 1);
			return 0;
		}
	}

	/* Withdraw bus requst */
	i2c_read(CONFIG_SYS_I2C_SII9022A_ADDR, TPI_SYS_CTRL_REG, 1, &data, 1);
	data &= ~(1 << 2);
	i2c_write(CONFIG_SYS_I2C_SII9022A_ADDR, TPI_SYS_CTRL_REG, 1, &data, 1);

	printf("Sii9022a: Failed to get DDC Bus\n");
	return -1;
}
